package com.eatme.web.sys.controller;

import com.alibaba.fastjson2.JSON;
import com.eatme.web.common.QueryCondition;
import com.eatme.web.common.vo.AppResponse;
import com.eatme.web.app.article.dao.model.UserVO;
import com.eatme.web.exception.DuplicateProblem;
import com.eatme.web.security.domain.vo.RefreshTokenRequest;
import com.eatme.web.security.domain.vo.UserRequest;
import com.eatme.web.sys.model.SysRole;
import com.eatme.web.sys.repository.SysUserRepository;
import com.eatme.web.util.jwt.JwtServiceImpl;
import com.eatme.web.app.article.service.SysUserService;
import com.eatme.web.sys.model.AuthUser;
import com.eatme.web.sys.model.RoleVO;
import com.eatme.web.sys.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/user/")
public class SysUserController {

    private static final Logger LOG = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService userServiceImpl;

    @Autowired
    private com.eatme.web.sys.service.SysUserService sysUserServiceImpl;

    @Autowired
    private JwtServiceImpl securitySysUserServiceImpl;

    @Autowired
    SysUserRepository sysUserRepository;

    @RequestMapping( "profile")
    @ResponseBody
    public AppResponse info(Authentication authentication){
        com.eatme.web.sys.entity.SysUser sysUser =  sysUserServiceImpl.getUserInfo(authentication.getName());
        return AppResponse.ok().data(sysUser);
    }

    @RequestMapping( "list")
    @ResponseBody
    public AppResponse list(@RequestBody QueryCondition<com.eatme.web.sys.entity.SysUser> queryCondition){
      return AppResponse.ok().data(userServiceImpl.findList(queryCondition));
    }

    @RequestMapping( "detail/{id}")
    @ResponseBody
    public AppResponse detail(@PathVariable(value = "id") Integer id){
        com.eatme.web.sys.entity.SysUser sysUser =  userServiceImpl.detail(id);
        return AppResponse.ok().data(sysUser);
    }

    @RequestMapping( "role/{id}")
    @ResponseBody
    public AppResponse role(@PathVariable(value = "id") Integer id){
        com.eatme.web.sys.entity.SysUser userVO  =  userServiceImpl.findRole(id);
        return AppResponse.ok().data(userVO);
    }

    @RequestMapping( "change-role/{id}")
    @ResponseBody
    public AppResponse role(@PathVariable(value = "id" )Integer id, @RequestBody Set<com.eatme.web.sys.entity.SysRole> roles){
        com.eatme.web.sys.entity.SysUser sysUser = userServiceImpl.detail(id);
        sysUser.getSysRoles().clear();
        sysUser.setSysRoles(roles);
        AppResponse result = userServiceImpl.updateUserRole(sysUser);
        return result;
    }

    @RequestMapping( "delete/{id}")
    @ResponseBody
    public AppResponse delete(@PathVariable(value = "id" )Integer id){
        return userServiceImpl.delete(id);
    }

    @RequestMapping( "add")
    @ResponseBody
    public AppResponse addUser(@RequestBody com.eatme.web.sys.entity.SysUser user){
        return sysUserServiceImpl.add(user);
    }

    @RequestMapping( "export")
    @ResponseBody
    public AppResponse export(){
        AppResponse r = sysUserServiceImpl.export();
        return r;
    }

    @RequestMapping( "batch/import")
    @ResponseBody
    public AppResponse batchImport(@RequestBody List<com.eatme.web.sys.entity.SysUser> list){
        AppResponse r = sysUserServiceImpl.batchImport(list);
        return r;
    }

    @PostMapping( "register")
    @ResponseBody
    public AppResponse register(@RequestBody UserRequest userDto){
        if (sysUserServiceImpl.isUsernameExisted(userDto.getUsername())) {
            throw new DuplicateProblem("用户名重复");
        }
        if (sysUserServiceImpl.isEmailExisted(userDto.getEmail())) {
            throw new DuplicateProblem("邮箱重复");
        }
        if (sysUserServiceImpl.isTelephoneExisted(userDto.getTelephone())) {
            throw new DuplicateProblem("联系方式重复");
        }
        SysUser user = new SysUser();
        user.setUsername(userDto.getUsername());
        user.setTelephone(userDto.getTelephone());
        user.setPassword(userDto.getPassword());
        com.eatme.web.sys.entity.SysUser sysUser = new com.eatme.web.sys.entity.SysUser();
        sysUser.setUsername(userDto.getUsername());
        sysUser.setPassword(userDto.getPassword());
        sysUser.setTelephone(userDto.getTelephone());
        sysUser.setMail(userDto.getEmail());
        sysUser.setStatus(1);
        AppResponse appResponse = sysUserServiceImpl.add(sysUser);
        return AppResponse.ok().data(appResponse.getData());
    }

    @PostMapping( "refresh")
    @ResponseBody
    public AppResponse refreshToken(
            @RequestHeader(name = "Authorization")String authorization,
                                    @RequestBody RefreshTokenRequest user) throws AccessDeniedException {
        String PREFIX = "Bearer ";
        // String refreshToken = user.getRefreshToken();
        String refreshToken = authorization.replace(PREFIX, "");
        return securitySysUserServiceImpl.refreshToken(refreshToken);
    }

    @RequestMapping( "query")
    @ResponseBody
    public AppResponse query(@RequestBody QueryCondition<com.eatme.web.sys.entity.SysUser> queryCondition){
        return userServiceImpl.query(queryCondition);
    }


}
